package com.qiaoya.deviceProxy;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import com.qiaoya.model.dto.JsonResult;
import com.qiaoya.model.entity.WatchCommandEntity;
import com.qiaoya.service.HealthDataService;

import io.swagger.annotations.ApiOperation;

@Component
public class ServerHandler extends IoHandlerAdapter {
	@Autowired
	protected HealthDataService healthDataService;

	private static ServerHandler  serverHandler ;
	
//	public void setTestService(HealthDataService  healthDataService) {  
//        this.healthDataService = healthDataService;  
//    }
	
	@PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
    public void init() {  
		serverHandler = this;  
		serverHandler.healthDataService = this.healthDataService;   // 初使化时将已静态化的testService实例化
    }  
	
//	@ApiOperation(value = "活力养生多级目录列表", notes = "活力养生多级目录列表", produces = MediaType.APPLICATION_JSON_VALUE)
//	@GetMapping("/dirs")
//	public JsonResult<Object> getDirsList(){
//		System.out.println(healthDataService.getClass());
//		healthDataService.insertPulse("1", "2", "2", 1);
//		return null;
//	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
		// ip:session
		String ip = session.getRemoteAddress().toString();
		if (!MsgLinkService.connectClient.containsKey(ip)) {
			MsgLinkService.connectClient.put(ip, session);
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String strMsg = message.toString();
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String TimeString = time.format(new java.util.Date());
		System.out.println("msgserver recv data from remove server---"+ TimeString+":" + strMsg);
		if(strMsg.contains("{") && strMsg.contains("}") && strMsg.contains(":")){
			processPacketHandler(strMsg.substring(1, strMsg.length() - 1), session);
		}
	}

	public void processPacketHandler(String strCommand, IoSession session) {
		if ("".equals(strCommand) || strCommand == null) {			
			return;
		}
		String[] command =  strCommand.split(":",7);
		if(command.length<6){
			return;
		}
		WatchCommandEntity recvCommand = new WatchCommandEntity(command);
		String commandType = recvCommand.getCommandType();
		if ("T1".equalsIgnoreCase(commandType)) {// 终端登录watch login
			// TODO:1.验证手表是否已经注册？2.通过验证的返回登录成功，未登录通过的失败，并切断连接
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S1");
			ArrayList<String> ayy = new ArrayList<String>();
			if (ayy != null) {
				ayy.add("1");
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				ayy.add(df.format(new Date()));
			}
			sendCommand.setParameters(ayy);
			System.out.println("S1,return to T1:"+sendCommand.toString());
			session.write(sendCommand.toString());
		} else if ("T2".equalsIgnoreCase(commandType)) {// 连接心跳connect Heart
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S28");
			ArrayList<String> ayy = sendCommand.getParameters();
			String location = "";
			String strLBS = ayy.get(1);				
			String timstamp = ayy.get(2);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long lt = new Long(Long.parseLong(timstamp));
			Date date = new Date(lt*1000L);
			String strTime = simpleDateFormat.format(date);// 测量的时间				
			location = serverHandler.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
			ayy.clear();
			// TODO:根据坐标返回详细地址信息
			ayy.add(location.replaceAll(" ", ""));
			sendCommand.setCommandType("S2");
			sendCommand.setParameters(ayy);
			System.out.println("S2,return to T2:"+sendCommand.toString());
			session.write(sendCommand.toString());
			
		} else if ("T5".equalsIgnoreCase(commandType)) {// 终端应答获取实时脉搏请求，answer to heartbeat requestc
			return;
		} else if ("T28".equalsIgnoreCase(commandType)) {// 终端上传脉搏数据，watch
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S28");
			ArrayList<String> ayy = sendCommand.getParameters();
			if (ayy != null) {
				if ("1".equalsIgnoreCase(ayy.get(0))) {// 实时数据
//					String strPulse = ayy.get(1);
//					String timstamp = ayy.get(2);
//					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					long lt = new Long(Long.parseLong(timstamp));
//					Date date = new Date(lt*1000L);
//					String strTime = simpleDateFormat.format(date);// 测量的时间
//					//// TODO:实时数据处理
//					System.out.println(strPulse.split("\\|")[0]);
//					serverHandler.healthDataService.insertPulse(sendCommand.getImei(), strPulse.split("\\|")[0], strTime, 0);
					
				} else if ("2".equalsIgnoreCase(ayy.get(0))) {// 定时数据
					String strPulse = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					// TODO:定时数据处理
					serverHandler.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
				} else if ("3".equalsIgnoreCase(ayy.get(0))) {// 手动数据
//					String strPulse = ayy.get(1);
//					String timstamp = ayy.get(2);
//					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					long lt = new Long(Long.parseLong(timstamp));
//					Date date = new Date(lt*1000L);
//					String strTime = simpleDateFormat.format(date);// 测量的时间
//					//TODO:手动数据处理
//					serverHandler.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
				} else if ("4".equalsIgnoreCase(ayy.get(0))) {// 睡眠数据
					String strPulse = ayy.get(1);
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间
					// TODO:睡眠数据处理
					serverHandler.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
				}
				ayy.clear();
			}
			session.write(sendCommand.toString());

		} else if ("T13".equalsIgnoreCase(commandType)) {// 终端应答实时LBS请求，answer
															// to LBS request
			return;
		} else if ("T29".equalsIgnoreCase(commandType)) {// 终端上传LBS数据指令, watch
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S29");
			ArrayList<String> ayy = sendCommand.getParameters();
			String location = "";
			if (ayy != null) {
				if ("1".equalsIgnoreCase(ayy.get(0))) {// 实时数据
					String strLBS = ayy.get(1);				
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间				
					location = serverHandler.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
				} else if ("2".equalsIgnoreCase(ayy.get(0))) {// 定时数据
					String strLBS = ayy.get(1);				
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间				
					location = serverHandler.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
				} else if ("3".equalsIgnoreCase(ayy.get(0))) {// 代表实时wifi数据
					String strWifi = ayy.get(1);				
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间				
					location = serverHandler.healthDataService.insertWifi(sendCommand.getImei(), strWifi, strTime, 1);
				} else if ("4".equalsIgnoreCase(ayy.get(0))) {// 实时gps数据
					String strGPS = ayy.get(1);
					String[] strstrGPSData = strGPS.split("\\|");
					String strLongitude = strstrGPSData[0];
					String strLatitude = strstrGPSData[1];					
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间				
					serverHandler.healthDataService.insertGPS(sendCommand.getImei(), strLongitude, strLatitude, strTime, 1);
				} else if ("5".equalsIgnoreCase(ayy.get(0))) {// gps防盗数据
					String strGPS = ayy.get(1);
					String[] strstrGPSData = strGPS.split("\\|");
					String strLongitude = strstrGPSData[0];
					String strLatitude = strstrGPSData[1];					
					String timstamp = ayy.get(2);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					long lt = new Long(Long.parseLong(timstamp));
					Date date = new Date(lt*1000L);
					String strTime = simpleDateFormat.format(date);// 测量的时间				
					serverHandler.healthDataService.insertGPS(sendCommand.getImei(), strLongitude, strLatitude, strTime, 1);
				} else if ("6".equalsIgnoreCase(ayy.get(0))) {// sos定位数据
					//????
				}
				ayy.clear();
				//根据坐标返回详细地址信息
				ayy.add(location.replaceAll(" ", ""));
				sendCommand.setParameters(ayy);
			}
			System.out.println("S29,return to T29:"+getUTF8String(sendCommand.toString()));
			session.write(getUTF8String(sendCommand.toString()));
			
		} else if ("T50".equalsIgnoreCase(commandType)) {// 终端综合数据（计步/LBS/脉搏）定时上传指令
			WatchCommandEntity sendCommand = recvCommand.clone();
			sendCommand.setCommandType("S50");
			ArrayList<String> ayy = sendCommand.getParameters();
			if(ayy.isEmpty()||ayy.size()<7){
				ayy.clear();
				System.out.println("S50,return to T50:"+sendCommand.toString());
				session.write(sendCommand.toString());
				return;
			}
			String strLBS = ayy.get(4);
			String strPulse = ayy.get(5);
			String timstamp = ayy.get(6);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long lt = new Long(Long.parseLong(timstamp));
			Date date = new Date(lt*1000L);
			String strTime = simpleDateFormat.format(date);// 测量的时间
			//20170712 综合数据的定位数据格式有错误
//			if(!strLBS.equals(null) && !strLBS.equals("")){
//				//insert LBS
//				serverHandler.healthDataService.insertLBS(sendCommand.getImei(), strLBS, strTime, 1);
//			}
			if(!strPulse.equals(null) && !strPulse.equals("")){
				//insert pulse
				serverHandler.healthDataService.insertPulse(sendCommand.getImei(), strPulse, strTime, 0);
			}
			ayy.clear();
			System.out.println("S50,return to T50:"+sendCommand.toString());
			session.write(sendCommand.toString());
		} else if ("T45".equalsIgnoreCase(commandType)) {// 终端上传血压数据指令

		} else if ("T47".equalsIgnoreCase(commandType)) {// 终端获取天气指令

		} else if ("T18".equalsIgnoreCase(commandType)) {// 终端应答设置sos号码指令

		} else if ("T38".equalsIgnoreCase(commandType)) {// 终端应答设置步履年龄体重指令

		} else if ("T49".equalsIgnoreCase(commandType)) {// 终端回复语音对讲指令

		} else if ("T8".equalsIgnoreCase(commandType)) {// 终端回复分段定时指令

		} else if ("T51".equalsIgnoreCase(commandType)) {// 终端上传关机指令

		} else if ("T52".equalsIgnoreCase(commandType)) {// 终端回复设置脉搏安全阈值

		} else if ("T4".equalsIgnoreCase(commandType)) {// 终端回复设置地址指令

		} else if ("T53".equalsIgnoreCase(commandType)) {// 终端回复手表提醒指令

		} else if ("T61".equalsIgnoreCase(commandType)) {// 终端回复关注和点赞设置指令

		} else if ("T55".equalsIgnoreCase(commandType)) {// 终端回复消息指令

		} else if ("T56".equalsIgnoreCase(commandType)) {// 终端上传消息已读指令

		} else if ("T57".equalsIgnoreCase(commandType)) {// 终端回复设置电话号码指令

		} else if ("T58".equalsIgnoreCase(commandType)) {// 终端回复界面设置指令

		} else if ("T59".equalsIgnoreCase(commandType)) {// 终端上传血糖数据指令

		} else if ("T60".equalsIgnoreCase(commandType)) {// 终端回复积分设置指令

		} else if ("T64".equalsIgnoreCase(commandType)) {// 终端回复积分设置指令

		} else if ("T63".equalsIgnoreCase(commandType)) {// 终端发送消息指令

		} else if ("T65".equalsIgnoreCase(commandType)) {// 终端获取积分，关注，点赞数据指令

		} else if ("T66".equalsIgnoreCase(commandType)) {// 终端回复设置终端时钟界面指令

		} else if ("T68".equalsIgnoreCase(commandType)) {// 终端回复设置防盗指令指令

		} else if ("T69".equalsIgnoreCase(commandType)) {// 终端应答实时温度和紫外线上传指令指令

		} else if ("T70".equalsIgnoreCase(commandType)) {// 终端应答工作模式设置指令指令

		} else if ("T71".equalsIgnoreCase(commandType)) {// 终端应答设置血压校准值指令指令

		} else if ("T72".equalsIgnoreCase(commandType)) {// 终端应答设置血压自动测量指令指令

		} else if ("T75".equalsIgnoreCase(commandType)) {// 终端开机图标指令

		} else if ("T65".equalsIgnoreCase(commandType)) {// 终端获取积分，关注，点赞数据指令

		} else {// 未知消息类型
			return;
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		super.messageSent(session, message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		super.sessionIdle(session, status);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		super.exceptionCaught(session, cause);
	}
	
	public static String getUTF8String(String srcStr) {  
	    // A StringBuffer Object  
	    StringBuffer sb = new StringBuffer();  
	    sb.append(srcStr);  
	    String xmString="";  
	    String strUTF8="";  
	    try {  
	    	xmString = new String(sb.toString().getBytes("UTF-8"));
	    	//strUTF8 = URLEncoder.encode(xmString, "UTF-8");
	    } catch (UnsupportedEncodingException e) {  
	    	e.printStackTrace();  
	    }   
	    return xmString;
	    } 
}
